package cn.heyige.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.heyige.backend.entity.AiMessageDO;
import cn.heyige.backend.mapper.AiMessageMapper;
import cn.heyige.backend.service.AiMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * AI消息服务实现类 - 精简版
 *
 * 专注于核心AI消息管理功能，提高系统性能和可维护性
 * 增强数据验证和错误处理
 *
 * @author CodeBuddy
 */
@Service("aiMessageService")
@Slf4j
@RequiredArgsConstructor
public class AiMessageServiceImpl extends ServiceImpl<AiMessageMapper, AiMessageDO> implements AiMessageService {
    
    private static final int DEFAULT_PAGE_SIZE = 20;
    private static final int MAX_PAGE_SIZE = 100;
    
    @Override
    public IPage<AiMessageDO> getMessagesBySessionId(String sessionId, Integer pageNum, Integer pageSize) {
        // 参数校验
        if (!StringUtils.hasText(sessionId)) {
            throw new IllegalArgumentException("会话ID不能为空");
        }

        // 设置默认分页参数
        int actualPageNum = pageNum != null ? pageNum : 1;
        int actualPageSize = pageSize != null ? Math.min(pageSize, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;

        try {
            return page(new Page<>(actualPageNum, actualPageSize),
                    new LambdaQueryWrapper<AiMessageDO>()
                            .eq(AiMessageDO::getSessionId, Integer.parseInt(sessionId))
                            .orderByAsc(AiMessageDO::getCreateTime));
        } catch (Exception e) {
            log.error("获取会话AI消息失败: sessionId={}, pageNum={}, pageSize={}",
                    sessionId, actualPageNum, actualPageSize, e);
            throw new RuntimeException("获取会话AI消息失败: " + e.getMessage());
        }
    }
    
    @Override
    public IPage<AiMessageDO> getMessagesByUserId(Long userId, Integer pageNum, Integer pageSize) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 设置默认分页参数
        int actualPageNum = pageNum != null ? pageNum : 1;
        int actualPageSize = pageSize != null ? Math.min(pageSize, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;

        try {
            return page(new Page<>(actualPageNum, actualPageSize),
                    new LambdaQueryWrapper<AiMessageDO>()
                            .orderByDesc(AiMessageDO::getCreateTime));
        } catch (Exception e) {
            log.error("获取AI消息失败: pageNum={}, pageSize={}",
                    actualPageNum, actualPageSize, e);
            throw new RuntimeException("获取AI消息失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessagesBySessionId(String sessionId) {
        // 参数校验
        if (!StringUtils.hasText(sessionId)) {
            throw new IllegalArgumentException("会话ID不能为空");
        }

        try {
            return remove(new LambdaQueryWrapper<AiMessageDO>()
                    .eq(AiMessageDO::getSessionId, Integer.parseInt(sessionId)));
        } catch (Exception e) {
            log.error("删除会话AI消息失败: sessionId={}", sessionId, e);
            throw new RuntimeException("删除会话AI消息失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessagesByUserId(Long userId) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        try {
            // 由于AiMessageDO中没有userId字段，所以这里直接返回false
            log.warn("AiMessageDO中没有userId字段，无法根据用户ID删除消息");
            return false;
        } catch (Exception e) {
            log.error("删除AI消息失败", e);
            throw new RuntimeException("删除AI消息失败: " + e.getMessage());
        }
    }
}
